﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

namespace CommonHelper
{
    public static class ResourcesHelper
    {
        /// <summary>
        /// 将程序集中的资源复制到计算机指定目录
        /// </summary>
        /// <param name="resourcePath">资源路径</param>
        /// <param name="savePath">存储路径</param>
        public static void CopyResource(Assembly assembly,string resourcePath, string savePath)
        {
            //string savepath = AppDomain.CurrentDomain.BaseDirectory + "Log4net.config";
            //根据名称空间和文件名生成资源名称
            //string resourceName = MethodBase.GetCurrentMethod().DeclaringType.Namespace + ".Log4net.config";
            if (!File.Exists(savePath))
            {
                
                Stream resourceStream = assembly.GetManifestResourceStream(resourcePath);
                //Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourcePath);
                Stream SavefileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write);

                resourceStream.Seek(0, SeekOrigin.Begin);
                resourceStream.CopyTo(SavefileStream);

                SavefileStream.Close();
                resourceStream.Close();
            }
        }
        public static void CopyResourceToRootPath(Assembly assembly, string resourcePath)
        {
            string savePath=AppDomain.CurrentDomain.BaseDirectory+ GetResourceFileName(resourcePath);
            //string savepath = AppDomain.CurrentDomain.BaseDirectory + "Log4net.config";
            //根据名称空间和文件名生成资源名称
            //string resourceName = MethodBase.GetCurrentMethod().DeclaringType.Namespace + ".Log4net.config";
            if (!File.Exists(savePath))
            {
                Stream resourceStream = assembly.GetManifestResourceStream(resourcePath);
                Stream SavefileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write);

                resourceStream.Seek(0, SeekOrigin.Begin);
                resourceStream.CopyTo(SavefileStream);

                SavefileStream.Close();
                resourceStream.Close();
            }
        }
        /// <summary>
        /// 获取资源的文件名称
        /// </summary>
        /// <param name="resourcePath">资源路径</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static string GetResourceFileName(string resourcePath)
        {
            string[] strings= resourcePath.Split('.');
            int l = strings.Length;
            if (strings.Length>=2)
            {
                return strings[l-2]+"."+ strings[l - 1];  
            }
            else
            {
                throw new Exception($"资源路径不正确 {resourcePath}");
            }
        }
    }
}
